<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import eventBus  from '../../event/eventBus.js';
import { Location } from '@element-plus/icons-vue'
import MarkIcon from '../../assets/image/watericon6.png'
import TaskFly from '@/utils/taskFly'
import Kjyc from './kjyc.js'
import $ from 'jquery';
import { ElMessage } from "element-plus";
const NAME = '飞行浏览';

let isFly = ref(false);
const { appContext } = getCurrentInstance();
let global = appContext.config.globalProperties;
let handler = null;
let _drawLayer;
let _last_clickTime;
let _last_clickPositionX;
let _last_clickPositionY;
let currOverlayArr = [];
let moveObj = null
let height = 40;

let tooltip = document.createElement('DIV');
document.body.appendChild(tooltip);
tooltip.style =
    'position: absolute;background: rgba(0,0,0,0.5); z-index: 999;line-height: 18px;pointer-events: none;';
tooltip.innerHTML =
    '<span style="color: #fff; font-size: 12px;padding:4px">单击开始，双击结束</span>'
tooltip.style.display = 'block'

const flyData = ref([
  // { lon: '', lat: '', height: '', speed: '', heading: '', pitch: '', distance: '' },
  // { lon: '', lat: '', height: '', speed: '', heading: '', pitch: '', distance: '' },
])
const kjyc = ref(null);

onMounted(() => {
  eventBus.on('mapToolBarClick', (data) => {
    if(data == NAME){
      isFly.value = !isFly.value;
    }else{
      isFly.value = false;
      removeOverlay()
      removeFly()
    }
  });
});
const subPoint = () => {
  console.log(flyData.value)
  // fly()
  if (flyData.value.length >= 2) {
    if (!kjyc.value) {
      kjyc.value = new Kjyc(global.$viewer, flyData.value);
    }
    kjyc.value.initFly();
  } else {
    ElMessage({
        message: '请添加飞行点',
        type: 'warning'
    })
  }
}
const fly = () => {
  removeLine()
  let line = []
  let height = 10
  if (flyData.value.length > 0) {
    flyData.value.forEach((item) => {
      line.push([item.lon, item.lat, height])
    })
    moveObj = new TaskFly(global.$viewer, line)
  } else {
    ElMessage({
        message: '请添加飞行点',
        type: 'warning'
    })
  }
}
const removeLine = () => {
  moveObj && moveObj.clear()
  moveObj = null
}
const removeFly = () => {
  kjyc.value && kjyc.value.destroy()
  kjyc.value = null;
}
const addPoint = () => {
  removeOverlay()
  removeFly()
  distance()
}
// 测量结果的浮窗
function markerOverlay(position) {
    if (global.$viewer) {
        let divStr = `<div class="marker" style="position: absolute;width: 14px;
          height: 20px;
          cursor: pointer;
          background-repeat: no-repeat;
          background-size: 20px 20px;
          background-position: -4px;
          background-image: url(${MarkIcon});"></div>`;
        let element = $(divStr)[0];
        let currOverlay;
        let option = {
            element: element,
            position: position,
            offset: { //默认整个div的左上角，跟地图上指定的点重合
                x: -6, //向屏幕左边平移的像素值
                y: -20 //向屏幕下方平移的像素值
            }
        };
        currOverlay = new Cesium.Overlay(option);
        currOverlayArr.push(currOverlay)
        global.$viewer.addOverlay(currOverlay);
    }
}
const getPoint = (call) => {
  // 地形拾取：
  handler = new Cesium.ScreenSpaceEventHandler(global.$viewer.canvas);
  handler.setInputAction((event) => {
      let ray = global.$viewer.camera.getPickRay(event.position);
      let c3 = global.$viewer.scene.globe.pick(ray,global.$viewer.scene);
      let cartographic= Cesium.Cartographic.fromCartesian(c3);
      let lat = Cesium.Math.toDegrees(cartographic.latitude);
      let lng = Cesium.Math.toDegrees(cartographic.longitude);
      // console.log(lng.toFixed(6)+', '+ lat.toFixed(6))
      call(lng.toFixed(6), lat.toFixed(6))
      removeHandlers()
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  handler.setInputAction(function (movement) {
      setTooltipPos(movement) // 设置tooltip位置
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
// 空间距离
function distance() {
    m_start() // 量算开启状态
    if (global.$viewer) {
        let positions = [],
            _lineEntity = new Cesium.Entity(),
            lineObj;
        handler = new Cesium.ScreenSpaceEventHandler(global.$viewer.scene.canvas);

        // left
        handler.setInputAction(function (movement) {
            // 连续单击或者双击，不处理后面一个点
            if (isNearPoint(movement)) {
                return
            }

            let cartesian = pickPosition(movement.position);
            if (cartesian && cartesian.x) {
                if (positions.length == 0) {
                    positions.push(cartesian.clone());
                }

                // _addInfoPoint(cartesian)
                markerOverlay(cartesian)

                let pickLngLats = pickLngLat(movement.position);
                let lng = pickLngLats.lng;
                let lat = pickLngLats.lat;
                if (flyData.value.length === 0) {
                  flyData.value.push({ lon: lng, lat: lat, height: height, speed: '', heading: '', pitch: '', distance: '' })
                } else {
                  let pts = [
                    pickPositionC3(flyData.value[flyData.value.length - 1].lon, flyData.value[flyData.value.length - 1].lat),
                    pickPositionC3(lng, lat)
                  ]
                  let result = Cesium.Measure.formatDistance(Cesium.Measure.getDistance(pts), 'auto');
                  // console.log(result)
                  if (result.includes('米')) {
                    result = parseFloat(result).toFixed(2)
                  } else if (result.includes('公里')) {
                    result = (parseFloat(result) * 1000).toFixed(2)
                  }
                  flyData.value.push({ lon: lng, lat: lat, height: '', speed: '', heading: '', pitch: '', distance: parseFloat(result) })
                }
                positions.push(cartesian);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        handler.setInputAction(function (movement) {
            setTooltipPos(movement) // 设置tooltip位置

            let cartesian = pickPosition(movement.endPosition);
            if (positions.length >= 2) {
                if (cartesian && cartesian.x) {
                    positions.pop();
                    positions.push(cartesian);
                }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // double-left
        handler.setInputAction(function (movement) {
            // let cartesian = pickPosition(movement.position);
            // _addDeletePoint(cartesian)
            m_end(); // 量算结束状态
        }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

        _lineEntity.polyline = {
            width: 2,
            material: Cesium.Color.fromCssColorString('#00ff00'),
        }
        _lineEntity.polyline.positions = new Cesium.CallbackProperty(function () {
            return positions
        }, false)

        lineObj = _drawLayer.entities.add(_lineEntity)
    }
}
function m_start() {
    if (global.$viewer) {
        if (!_drawLayer) {
            _drawLayer = new Cesium.CustomDataSource('drawLayer')
            global.$viewer.dataSources.add(_drawLayer);
        }
    }
    document.body.style.cursor = "crosshair"
    removeHandlers();
    showTooltip() // 显示tooltip提示
}
function m_end() {
    document.body.style.cursor = "default"
    removeHandlers();
    hideTooltip() // 隐藏tooltip提示
}
function removeHandlers() {
    handler && handler.destroy();
    handler = null;
}
function isNearPoint(movement) {
    let times = new Date().getTime() - (_last_clickTime || 0);
    if (_last_clickTime && times < 200) {
        // console.log('屏蔽了单击时间很近的点')
        return true;
    }
    _last_clickTime = new Date().getTime();

    if (
        _last_clickPositionX &&
        Math.abs(_last_clickPositionX - movement.x) < 10 &&
        Math.abs(_last_clickPositionY - movement.y) < 10
    ) {
        // console.log('屏蔽了单击像素很近的点')
        return true;
    }
    _last_clickPositionX = movement.x;
    _last_clickPositionY = movement.y;
    return false;
}
// 获取坐标
function pickPosition(position) {
    let ray = global.$viewer.camera.getPickRay(position);
    let c3 = global.$viewer.scene.globe.pick(ray, global.$viewer.scene);
    let cartographic= Cesium.Cartographic.fromCartesian(c3);
    let lat = Cesium.Math.toDegrees(cartographic.latitude);
    let lng = Cesium.Math.toDegrees(cartographic.longitude);
    let p = Cesium.Cartesian3.fromDegrees(lng, lat, height);
    return p
}
// 获取坐标
function pickLngLat(position) {
    let ray = global.$viewer.camera.getPickRay(position);
    let c3 = global.$viewer.scene.globe.pick(ray, global.$viewer.scene);
    let cartographic= Cesium.Cartographic.fromCartesian(c3);
    let lat = Cesium.Math.toDegrees(cartographic.latitude);
    let lng = Cesium.Math.toDegrees(cartographic.longitude);
    return { lng, lat }
}
// 获取坐标
function pickPositionC3(lng, lat) {
    return Cesium.Cartesian3.fromDegrees(lng, lat, height)
}
function setTooltipPos(movement) {
    tooltip.style.left = movement.endPosition.x + 10 + 'px'
    tooltip.style.top = movement.endPosition.y - 27 + 'px'
}
function showTooltip() {
    tooltip.style.display = 'block'
}
function hideTooltip() {
    tooltip.style.display = 'none'
}
// 清除
function removeOverlay() {
    if (_drawLayer) {
        _drawLayer.entities.removeAll();
    }
    if (currOverlayArr.length) {
        currOverlayArr.forEach(item => {
            item&&item.destroy();
        })
        currOverlayArr = [];
    }
    m_end()
    removeLine()
    flyData.value = []
}
</script>

<template >
  <div v-if="isFly" class="fly" style="box-shadow: var(--el-box-shadow-light)">
    <div class="title">飞行浏览预</div>
    <div class="content">
      <div class="item" v-for="(item, index) in flyData" :key="item">
        <div class="name">定位点{{ index+1 }}</div>
        <div class="subname">
          <span>添加经纬度</span>
          <span><el-icon><Location /></el-icon></span>
        </div>
        <div class="item-value">
          <el-input v-model="item.lon" disabled />
          <el-input v-model="item.lat" disabled />
        </div>
        <div class="other" v-if="index === 0">
          <span>高度/速度（m）/（m/s）</span>
          <div class="item-value">
            <el-input v-model="item.height" placeholder="高度" />
            <el-input v-model="item.speed" placeholder="速度" />
          </div>
        </div>
        <div class="other" v-if="index === 0">
          <span>添加航向角（°）/俯仰角（°）</span>
          <div class="item-value">
            <el-input v-model="item.heading" placeholder="航向角" />
            <el-input v-model="item.pitch" placeholder="俯仰角" />
          </div>
        </div>
        <div class="other" v-if="index > 0">
          <span>距离（m）</span>
          <div class="item-value">
            <el-input v-model="item.distance" disabled />
          </div>
        </div>
      </div>
      <div class="non-data" v-if="flyData.length === 0">暂无数据</div>
    </div>
    <div class="footer">
      <el-button type="primary" @click="addPoint">添加</el-button>
      <el-button @click="subPoint">确定</el-button>
    </div>
  </div>
</template>
<style lang="less" scoped>
.fly {
  background: rgba(8,22,56, 0.9);
  border-radius: 0.2rem;
  color: #fff;
  .title {
    text-align: center;
    font-size: 0.9rem;
    padding: 0.6rem 0;
    border-bottom: 0.05rem solid #808080;
  }
  .content {
    width: 14rem;
    height: 24rem;
    overflow: auto;
    padding: 0.6rem;
    font-size: 0.9rem;
    .item {
      border-bottom: 0.05rem dashed #808080;
      padding-bottom: 10px;
      margin-bottom: 10px;
      &:last-child {
        border: none;
      }
      .name {
        position: relative;
        padding-left: 12px;
        &::before {
          content: "";
          position: absolute;
          top: 2px;
          left: 0;
          width: 4px;
          height: 12px;
          background: #F3BB46;
        }
      }
      .subname {
        margin-top: 6px;
        display: flex;
        align-items: center;
        span:last-child {
          width: 2rem;
          display: inline-flex;
          align-content: center;
          justify-content: center;
          color: #fff;
          border-radius: 2px;
          background: #169BD5;
          margin-top: 1px;
          margin-left: 5px;
          font-size: 9px;
          padding: 2px 0;
        }
      }
      .other {
        margin-top: 6px;
      }
      .item-value {
        display: flex;
        justify-content: space-between;
        margin-top: 4px;
        ::v-deep(.el-input) {
          width: calc(50% - 5px);
          .el-input__wrapper {
            background-color: #133C57 !important;
            box-shadow: none;
          }
          .el-input__inner {
            font-size: 10px;
            color: #a8abb2;
          }
        }
      }
    }
  }
  .footer {
    padding: 0.6rem 0;
    border-top: 0.05rem solid #808080;
    text-align: center;
  }
}
.non-data {
  color: #999;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>